import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../core/constants.dart';
import '../../core/themes.dart';
import '../../data/models/puzzle_piece.dart';

/// 拼图块组件
class PuzzlePieceWidget extends StatefulWidget {
  final PuzzlePiece piece;
  final String imagePath;
  final Size boardSize;
  final bool isBeingDragged;
  final Function(Offset) onDragStart;
  final Function(Offset) onDragUpdate;
  final Function(Offset) onDragEnd;
  
  const PuzzlePieceWidget({
    super.key,
    required this.piece,
    required this.imagePath,
    required this.boardSize,
    required this.isBeingDragged,
    required this.onDragStart,
    required this.onDragUpdate,
    required this.onDragEnd,
  });
  
  @override
  State<PuzzlePieceWidget> createState() => _PuzzlePieceWidgetState();
}

class _PuzzlePieceWidgetState extends State<PuzzlePieceWidget> 
    with SingleTickerProviderStateMixin {
  
  // 动画控制器
  late AnimationController _scaleController;
  late Animation<double> _scaleAnimation;
  
  // 状态变量
  bool _isPressed = false;
  
  @override
  void initState() {
    super.initState();
    _initializeAnimations();
  }
  
  void _initializeAnimations() {
    _scaleController = AnimationController(
      duration: AppConstants.dragAnimationDuration,
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _scaleController,
      curve: Curves.elasticOut,
    ));
  }
  
  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: widget.piece.position.dx,
      top: widget.piece.position.dy,
      child: GestureDetector(
        onPanStart: _handlePanStart,
        onPanUpdate: _handlePanUpdate,
        onPanEnd: _handlePanEnd,
        onTapDown: (_) => _handleTapDown(),
        onTapUp: (_) => _handleTapUp(),
        onTapCancel: _handleTapUp,
        child: ScaleTransition(
          scale: _scaleAnimation,
          child: _buildPieceContainer(),
        ),
      ),
    );
  }
  
  /// 构建拼图块容器
  Widget _buildPieceContainer() {
    return Container(
      width: widget.piece.size.width,
      height: widget.piece.size.height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
        boxShadow: _buildBoxShadows(),
      ),
      child: ClipPath(
        clipper: PuzzlePieceClipper(widget.piece.clipPath),
        child: Stack(
          children: [
            // 拼图块图像
            _buildPieceImage(),
            
            // 选中状态遮罩
            if (widget.piece.isSelected)
              _buildSelectionOverlay(),
            
            // 正确放置状态指示器
            if (widget.piece.isPlaced)
              _buildPlacedIndicator(),
            
            // 拖拽状态边框
            if (widget.isBeingDragged)
              _buildDragBorder(),
          ],
        ),
      ),
    );
  }
  
  /// 构建拼图块图像
  Widget _buildPieceImage() {
    return Transform.translate(
      offset: Offset(
        -widget.piece.correctCol * widget.piece.size.width,
        -widget.piece.correctRow * widget.piece.size.height,
      ),
      child: Image.asset(
        widget.imagePath,
        width: widget.boardSize.width,
        height: widget.boardSize.height,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey.shade300,
            child: Center(
              child: Icon(
                Icons.broken_image,
                color: Colors.grey.shade500,
                size: widget.piece.size.width * 0.3,
              ),
            ),
          );
        },
      ),
    );
  }
  
  /// 构建选中状态遮罩
  Widget _buildSelectionOverlay() {
    return Container(
      decoration: BoxDecoration(
        color: GameColors.puzzlePieceSelected.withValues(alpha: 0.3),
        border: Border.all(
          color: GameColors.puzzlePieceSelected,
          width: 2,
        ),
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
  
  /// 构建正确放置指示器
  Widget _buildPlacedIndicator() {
    return Positioned(
      top: 4,
      right: 4,
      child: Container(
        padding: const EdgeInsets.all(2),
        decoration: BoxDecoration(
          color: GameColors.puzzlePiecePlaced,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.3),
              blurRadius: 2,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Icon(
          Icons.check,
          color: Colors.white,
          size: math.min(12, widget.piece.size.width * 0.2),
        ),
      ),
    );
  }
  
  /// 构建拖拽状态边框
  Widget _buildDragBorder() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: GameColors.dragFeedbackBorder,
          width: 3,
        ),
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
  
  /// 构建阴影效果
  List<BoxShadow> _buildBoxShadows() {
    if (widget.isBeingDragged) {
      // 拖拽时的强阴影
      return [
        BoxShadow(
          color: Colors.black.withValues(alpha: 0.3),
          blurRadius: 12,
          offset: const Offset(0, 8),
        ),
        BoxShadow(
          color: GameColors.dragFeedbackBorder.withValues(alpha: 0.2),
          blurRadius: 6,
          offset: const Offset(0, 4),
        ),
      ];
    } else if (widget.piece.isSelected || _isPressed) {
      // 选中或按下时的中等阴影
      return [
        BoxShadow(
          color: Colors.black.withValues(alpha: 0.2),
          blurRadius: 8,
          offset: const Offset(0, 4),
        ),
      ];
    } else if (widget.piece.isPlaced) {
      // 正确放置时的轻微阴影
      return [
        BoxShadow(
          color: GameColors.puzzlePiecePlaced.withValues(alpha: 0.3),
          blurRadius: 4,
          offset: const Offset(0, 2),
        ),
      ];
    } else {
      // 默认阴影
      return [
        BoxShadow(
          color: Colors.black.withValues(alpha: 0.1),
          blurRadius: 4,
          offset: const Offset(0, 2),
        ),
      ];
    }
  }
  
  // =================== 手势处理 ===================
  
  void _handlePanStart(DragStartDetails details) {
    if (widget.piece.isLocked) return;
    
    _scaleController.forward();
    widget.onDragStart(details.globalPosition);
  }
  
  void _handlePanUpdate(DragUpdateDetails details) {
    if (widget.piece.isLocked) return;
    
    widget.onDragUpdate(details.globalPosition - 
        Offset(widget.piece.size.width / 2, widget.piece.size.height / 2));
  }
  
  void _handlePanEnd(DragEndDetails details) {
    if (widget.piece.isLocked) return;
    
    _scaleController.reverse();
    widget.onDragEnd(widget.piece.position);
  }
  
  void _handleTapDown() {
    if (widget.piece.isLocked) return;
    
    setState(() {
      _isPressed = true;
    });
  }
  
  void _handleTapUp() {
    setState(() {
      _isPressed = false;
    });
  }
  
  @override
  void dispose() {
    _scaleController.dispose();
    super.dispose();
  }
}

/// 拼图块裁剪器
class PuzzlePieceClipper extends CustomClipper<Path> {
  final Path clipPath;
  
  const PuzzlePieceClipper(this.clipPath);
  
  @override
  Path getClip(Size size) {
    // V1.0版本使用简单的矩形裁剪
    // V2.0版本将使用复杂的拼图形状
    return clipPath;
  }
  
  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return oldClipper != this;
  }
}


